import ApiResult from "@/api/base/ApiResult";
import { request, post } from "@/utils/request";
import { IGoodsPageRow, IMallPageItem, IStoreGoodsDetail, IStoreProductRow } from "@/api/modules/pointsMall";
import { ElMessage } from "element-plus";
import { IAddProductForm } from "@/components/goodsCenter/types/addProductForm";
import { ComputedRef } from "vue";

/**
 * 新增规格
 */
export function useAddProduct() {
  const store = useStore()
  const form = reactive<IAddProductForm>({} as any)
  const formRef = ref()
  const storeProducts = ref<IStoreProductRow[]>([])

  const getStoreProducts = async (url: string, params: { id: number | null }) => {
    const rs: ApiResult<IStoreGoodsDetail> = await request(url, params)

    if (rs.code === 200) {
      if (rs.payload) {
        storeProducts.value = rs.payload.products ?? []
        // 添加供货价字段
        storeProducts.value = storeProducts.value.map(i => ({ ...i, costPrice: i.payPrice }))
      }
    }
  }

  const selectedStoreProduct = ref<IStoreProductRow | null>()
  const selectStoreProducts = (option: IStoreProductRow | null) => {
    selectedStoreProduct.value = option
    if (!option) {
      formRef.value?.resetFields()
      return
    }

    Object.keys(option).forEach(key => {
      form[key] = option[key]
    })

    form['addOrDeductionStockCount'] = form['addOrDeductionStockCount'] ?? 1
  }

  const formatData = ({ rowData, formProps }: { rowData: IGoodsPageRow, formProps: string[] }) => {
    form.storeGoodsId = form.goodsId
    form.storeProductId = selectedStoreProduct.value?.id
    form.goodsId = rowData.id
    form.id = null

    if (formProps.includes('mallId')) {
      const mallConfig: ComputedRef<IMallPageItem> = computed<IMallPageItem>(() => store.state.pointsMall.mallConfig)
      form.mallId = mallConfig.value.id
    }

    return [{ ...form }]
  }

  const submit = (url: string, data: any, options: { rowData: IGoodsPageRow, formProps: string[] }) => {
    return new Promise((resolve) => {
      formRef.value?.validate(async (valid: boolean, fields: any) => {
        if (valid) {
          const _form = formatData({
            rowData: options.rowData,
            formProps: options.formProps
          })
          //添加供货价字段
          _form.costPrice = selectedStoreProduct.costPrice
          const rs: ApiResult<any> = await request(url, _form)

          if (rs.code === 200) {
            ElMessage.success('保存成功')
            resolve(rs)
          }
        } else {
          console.log('valid failed', fields)
        }
      })
    })
  }

  const isShowAddProduct = ref(false)
  const currentGoodsRowForAddProduct = ref<IGoodsPageRow>()
  const showAddProduct = (rowData: IGoodsPageRow) => {
    isShowAddProduct.value = true
    currentGoodsRowForAddProduct.value = rowData
  }

  return {
    form,
    formRef,
    storeProducts,
    getStoreProducts,

    selectStoreProducts,
    selectedStoreProduct,

    submit,

    isShowAddProduct,
    currentGoodsRowForAddProduct,
    showAddProduct
  }
}
